<template>
  <ul>
    <li>name: <input type="text" v-model="name" /></li>
    <li>age: <input type="text" v-model="age" /></li>
    <li>salary: {{ job.salary }}</li>
  </ul>
  <!-- <input v-model="person.introduce" /> -->
  <button @click="++age">age++</button>
  <button @click="++job.salary">salary++</button>
  <h3>{{ count }}</h3>
  <button @click="++count">count++</button>
  <h3>{{ list }}</h3>
  <button @click="list[0]++">changeList</button>
  <h3>customRef</h3>
  <input type="text" v-model="customRefValue">
  <h4>{{ customRefValue }}</h4>
</template>

<script>
import {
  ref,
  reactive,
  computed,
  watch,
  watchEffect,
  toRef,
  toRefs,
  shallowReactive,
  shallowRef,
  readonly,
  shallowReadonly,
  toRaw,
  markRaw,
  customRef
} from 'vue'
export default {
  name: 'child',
  setup (props, context) {
    let person = shallowReactive({
      name: 'Tom',
      age: 20,
      job: {
        salary: 20
      }
    })
    let list = ref([1, 2, 3])
    list = readonly(list)

    // list[0] = 9

    person.introduce = computed({
      get () {
        return `Hi! I'm ${person.name} and ${person.age} year's old.`
      },
      set (value) {
        const info = value.split(' ')
        person.name = info[2]
        person.age = info[4]
      }
    })
    let p = toRaw(person)
    console.log(p)


    watch(
      () => person.job,
      (newVal, oldVal) => {
        console.log(newVal, oldVal)
      },
      { deep: true }
    )

    let count = ref(0)
    watch(count, (newVal, oldVal) => {
      console.log(newVal, oldVal)
    })

    // watch(
    //   person,
    //   (newVal, oldVal) => {
    //     console.log(newVal, oldVal)
    //   },
    //   { deep: true }
    // )

    watchEffect(() => {
      let a = person.age
      let b = count.value
      // console.log(1)
    })

    function myRef (value) {
      let timer = null
      return customRef((track, trigger) => ({
        get () {
          track() // 通知 Vue 追踪 value 的变化
          return value
        },
        set (newValue) {
          clearTimeout(timer)
          timer = setTimeout(() => {
            value = newValue
            trigger() // 通知 Vue 重新解析模板
          }, 1000)
        }
      }))
    }

    let customRefValue = myRef(123)

    return {
      // name: toRef(person, 'name'),
      // age: toRef(person, 'age'),
      // salary: toRef(person.job, 'salary'),
      // introduce: toRef(person, 'introduce'),
      ...toRefs(person),
      count,
      list,
      customRefValue
    }
  }
}
</script>
